Ploty Package - An Introduction
Introduction
Today, we will cover the “plotly” package and explore it using a variety of data sets. First, we will start by uploading the packages that will be needed today. If these packages do not load, be sure to install them.
Functions
This package can be used in a variety of ways to make data interactive and fun. The functions we will be exploring today are:
- add_surface
- plot_ly
- animation
- add_trace
- colorbar
- layout
- add_text
library(plotly)
library(tidyverse)
library(here)
library(readr)
library(maps)
library(dplyr)
library(ggplot2)
library(lubridate)
library(purrr) #Used to create the animation frames
library(rmdformats)
library(heatmaply)
library(palmerpenguins)
library(reticulate)3D Chart Example
Load Data
CherryTree_Data_ <- read_csv(here("Data/CherryTree Data .csv")) # Load dataChange to a numeric matrix
CherryTree <- as.matrix(CherryTree_Data_) # change the data set to a numeric matrix Plot numeric matrix
fig <- plot_ly(z = ~CherryTree) # plot by numeric matrix
fig<- fig %>% add_surface()View figure
fig # Display plotAn example of an animation timeseries
data("economics") # Load in dataset that is already built into RMutate Data
econ <- economics %>% # Subset data
mutate(cumulative_pop = cumsum(pop)) # Creates a new columnCreate a filled area plot with an animation frame
econ %>%
plot_ly(x = ~date, # Specify x and y variables of interest
y = ~cumulative_pop,
fill = ~pop,
type = "scatter", # Insert graph type
mode = "none",
stackgroup = "one",
animation_frame = ~year(date)) %>% #
add_trace(y = ~0,
hoverinfo = "skip",
showlegend = FALSE) %>%
layout(title = "US Population Over Time",
xaxis = list(title = "Date"),
yaxis = list(title = "Cumulative Population")) %>%
colorbar(title = "Population", len = 0.5, y = 0.8, ypad = 0)Our goal is to look at the median population data for the state of California from 2000 and 2010. Note: Plotly has built-in Country and State Geometries.
Now let’s explore another graph type with this package. We will create a scatter plot with this data to create interactive points.
Load Data
chemicaldata <- read_csv(here("Data/chemicaldata.csv")) # Load dataCreate a scatter mapbox plot with the latitude and longitude data
fig <- plot_ly(chemicaldata, type = "scattermapbox", # Specify df, graph type, and etc.
mode = "markers",
marker = list(size = 10,
color = "red"),
lon = ~Long, lat = ~Lat)Set the map layout
fig <- fig %>% layout(mapbox = list(center = list(lon = -157.763,
lat = 21.274),
zoom = 15,
style = "open-street-map"))Show the map
fig # Show the map2D Histogram Example Using Penguin Data
plot_ly(
data = penguins,
alpha = 0.6,
x = ~bill_depth_mm,
y = ~species,
type = "histogram2d",
text = ~paste('</br> species:', species,
'</br> bill depth', bill_depth_mm)) %>%
layout(title = "A Measure of Penguin Bill Depth and Islands",
xaxis = list(title = "Bill Depth (mm)"),
yaxis = list(title = "Species"))Heatmap example using penguin data (need to make more edits)
penguinplot <- as.matrix(penguins_raw) # Change data set to matrix
fig<- plot_ly(z = ~penguinplot, type = "heatmap") View Plot
figBar Chart
Load Data
data("msleep") # Load dataCreate bar plot
sleep_bar <-msleep %>%
plot_ly(x = ~order,
y = ~sleep_rem,
type = "bar",
name = "REM Sleep")Add layout information
sleep_bar <- sleep_bar %>%
layout(title = "Average REM Sleep by Order",
xaxis = list(title = "Animal Order"),
yaxis = list(title = "REM Sleep (hours)"))Show plot
sleep_barLoad Data
data(msleep) # Load DataSubset data set
msleep <- ggplot2::msleep %>% # we need to assign the data set "msleep" found in ggplot and assign it to our current RMarkdown.
rename(`Type of Diet` = vore, `Total Hours of Sleep` = sleep_total) %>% #changes names before making graph so axis doesn't need to be changed later
na.omit() #removes any incomplete or N/A data from data setCreate a bar graph
diet_sleep <- msleep %>% # We have assigned our graph the letter Q to request it easily later
plot_ly(x = ~reorder(`Type of Diet`, -`Total Hours of Sleep`),
y = ~`Total Hours of Sleep`, # changing the order of how the bars show up so they're increasing in hours of sleep.
type = 'bar', # type of graph
marker = list(color = rainbow(nrow(msleep), #uses rainbow colors for bars indicating their sleeping hours individually and as a dietary group.
alpha = 0.7))) %>% #determines the transparency/opacity of the bars 0.0 being completely transparent
layout(xaxis = list(title = "Type of Diet"), #naming x-axis
yaxis = list(title = "Total Hours of Sleep"), #naming y-axis
title = "Total Hours of Sleep vs. Type of Diet") #naming graphAnimating your Graph
# Add animation to the bars
diet_sleep <- diet_sleep %>%
animation_opts(frame = 100, easing = 'elastic') #controls timing and style of animation,Displaying our Results
# Display the graph
diet_sleep